package com.cqeec.myblog.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.cqeec.myblog.model.Category;
import com.cqeec.myblog.util.DbUtil;

public class CategoryDaoImpl implements CategoryDao{
	

	@Override
	public List<Category> selectAllCategory() {
		try {
			Connection con=DbUtil.getDbConnection();
			PreparedStatement ps=con.prepareStatement("select * from category");
			ResultSet rs=ps.executeQuery();
			List<Category> list=new ArrayList<>();
			while (rs.next()) {
				Category category=new Category();
				String id=rs.getString("id");
				String name=rs.getString("name");
				category.setId(id);
				category.setName(name);
				list.add(category);
			}
			return list; 
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public void deleteCategoryByCid(String cid) {
		try {
			Connection con=DbUtil.getDbConnection();
			PreparedStatement ps=con.prepareStatement("delete from category where id = ?");
			ps.setString(1, cid);
			ps.execute();
		} catch (Exception e) {
			
		}
	}

	@Override
	public void addCategory(String cid, String cname) {
		try {
			Connection con=DbUtil.getDbConnection();
			PreparedStatement ps=con.prepareStatement("insert into category(id,name)values(?,?)");
			ps.setString(1, cid);
			ps.setString(2, cname);
			ps.execute();
		} catch (Exception e) {
			
		}
	}

	@Override
	public Category findByCname(String cname) {
        		try {
        			Connection con=DbUtil.getDbConnection();
        			PreparedStatement ps=con.prepareStatement("select * from category where name=?");
        			ps.setString(1, cname);
        			ResultSet rs=ps.executeQuery();
        			rs.next();
        			Category category=new Category();
        			category.setId(rs.getString("id"));
        			category.setName(rs.getString("name"));
        			return category;
				} catch (Exception e) {
					// TODO: handle exception
					return null;
				}
	}

}
